#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 
###----------1、文件说明----------### 
''' 
* 说明：conan安装配置文件
* 时间：
* 文件：
* 作者：Smile
* 版本：0.1
* 模板版本: 0.2
 - 0.2 添加 source validate finalize等函数，修改获取系统信息功能的代码存放位置
* 库版本: 
 - conan: 2.14.0
* 备注： 
'''
import os,sys
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout, CMakeDeps
from conan.tools.system import package_manager
from pprint import pprint
import platform
import importlib
from datetime import datetime
import time
import shutil

def getClassValue(sclass):
    '''
    获取类的子属性
    版本: 0.1
    :param sclass:
    :return:
    '''
    from types import FunctionType, BuiltinFunctionType, MethodType

    print("Get Class ", type(sclass))
    for i in dir(sclass):
        tmp = getattr(sclass, i)
        if isinstance(tmp, FunctionType) or isinstance(tmp, BuiltinFunctionType):
            print(i, "\t", type(tmp), "Function")
        else:
            print(i, "\t", type(tmp), tmp)

manager_mapping = {"Apt": ["Linux", "ubuntu", "kylin", "debian", "raspbian", "linuxmint", 'astra', 'elbrus', 'altlinux', 'pop'],
                    "Apk": ["alpine"],
                    "Yum": ["pidora", "scientific", "xenserver", "amazon", "oracle", "amzn",
                            "almalinux", "rocky"],
                    "Dnf": ["fedora", "rhel", "centos", "mageia", "nobara"],
                    "Brew": ["Darwin"],
                    "PacMan": ["arch", "manjaro", "msys2", "endeavouros"],
                    "Chocolatey": ["Windows"],
                    "Zypper": ["opensuse", "sles"],
                    "Pkg": ["freebsd"],
                    "Pkgutil": ["Solaris"]}

class SoftConfigRecipe(ConanFile):
    name = "softinstall"
    version = "0.1"
    package_type = "build-scripts"

    # 个人信息
    license = "MIT"
    author = "<OSmile> <whghcyx@outlook.com>"
    url = "https://whg555.github.io"
    description = "readme description"
    topics = ("<Put some tag here>", "<here>", "<and here>")

    # 二进制配置
    settings = "os", "compiler", "build_type", "arch"

    def init(self):
        '''
        <1>conan create .
        <3>conan create .
        <1>conan install .
        :return:
        '''
        # 判断函数运行的时间
        self.starttime = datetime.now()
        # 判断函数调用顺序的变量
        if not hasattr(self, "runfunnum"):
            self.runfunnum = 0
        print("\033[43;34mOSmile-->", "init", "<" + str(datetime.now() - self.starttime) +  ">", "\033[0m")
        # 更新当前函数调用的
        self.runfunnum += 1
        # print("\033[43;34mOSmile-->", self.runfunnum, "\033[0m")
        # 创建缓存目录
        # self.tmppath = tempfile.mkdtemp()
        self.tmppath = os.path.join(os.path.expanduser("~"), "conantmp")
        os.makedirs(self.tmppath, exist_ok=True)

        # 获取系统版本信息
        os_name = platform.system()
        self.os_name = self.os_version = self.os_base = ""
        self.os_base = os_name
        if os_name in ["Linux", "FreeBSD"]:
            import distro
            self.os_name = distro.id() or os_name
            self.os_version = distro.version(best=True).split(".")[0]
        # elif os_name == "Windows" and self.settings.get_safe("os.subsystem") == "msys2":
        elif os_name == "Windows":
            self.os_name = "msys2"
            self.os_version = ""
        print("System   -->", self.os_base)    # Linux  Windows
        print("OSSystem -->", self.os_name)    # ubuntu msys2
        print("Version  -->", self.os_version) # 18
        print("TmpPath  -->", self.tmppath)    #

    def config_options(self):
        '''
        针对系统，对配置命令做一些修改
        <4>conan create .
        <2>conan install .
        <test><1>conan create .
        '''

        print("\033[43;34mOSmile-->", "config_options", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        # pprint(self.settings.values_list)
        # pprint(self.serialize())
        # print("self.conf", self.conf)
        # print("ARCH", self.settings.get_safe("arch"))
        # print("self.conf", self.conf.keys())

    def configure(self):
        '''
        <5>conan create .
        <3>conan install .
        <test><2>conan create .
        '''
        print("\033[43;34mOSmile-->", "configure", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        if self.os_name == "kylin":
            self.conf.define("tools.system.package_manager:tool", "apt-get")
        self.conf.define("tools.system.package_manager:mode", "install")
        self.conf.define("tools.system.package_manager:sudo", True)

    def generate(self):
        '''
        配置已经安装的软件
        <13>conan create .
        <9>conan install .
        '''
        print("\033[43;34mOSmile-->", "generate", "<" + str(datetime.now() - self.starttime) + ">", "\033[0m")
        # 特定的系统配置
        if self.os_base == "Windows":
            pass
        else: # Linux
            if self.os_name == "ubuntu":
                # 删除vmware的缓存目录
                self.run("rm -rf .cache/vmware/drag_and_drop/*", cwd=os.path.expanduser("~"))
                # 删除回收站中的内容
                self.run("rm -rf .local/share/Trash/files/*", cwd=os.path.expanduser("~"))
                self.run("rm -rf .local/share/Trash/info/*", cwd=os.path.expanduser("~"))

        if os.path.exists(self.tmppath):
            # 删除缓存目录
            shutil.rmtree(self.tmppath)

